package com.seal.commons.utils.security;


import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAUtils
{
    private static final int MAX_ENCRYPT_BLOCK = 117;
    private static final int MAX_DECRYPT_BLOCK = 128;

    public static final int KEY_SIZE_2048=2048;
    public static final int KEY_SIZE_1024=1024;

    public static KeyStore getKeyLibs(String keyStorePath, String password)
            throws Exception
    {
        FileInputStream is = new FileInputStream(keyStorePath);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(is, password.toCharArray());
        is.close();
        return ks;
    }

    public static Certificate getCertificate(String certificatePath)
            throws Exception
    {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        FileInputStream in = new FileInputStream(certificatePath);
        Certificate certificate = certificateFactory.generateCertificate(in);
        in.close();
        return certificate;
    }

    public static boolean verify(byte[] data, String sign, X509Certificate cert)
            throws Exception
    {
        PublicKey publicKey = cert.getPublicKey();

        Signature signature = Signature.getInstance(cert.getSigAlgName());
        signature.initVerify(publicKey);
        signature.update(data);
        return signature.verify(decryptBASE64(sign));
    }

    public static byte[] decryptBASE64(String key)
            throws Exception
    {
        return Base64.decodeBase64(key.getBytes());
    }

    public static byte[] encryptByPrivateKey(byte[] data, String keyStorePath, String alias, String password)
            throws Exception
    {
        FileInputStream is = new FileInputStream(keyStorePath);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(is, password.toCharArray());
        is.close();
        PrivateKey privateKey = (PrivateKey)ks.getKey(alias, password.toCharArray());

        Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
        cipher.init(1, privateKey);
        return cipher.doFinal(data);
    }

    public static String encryptBASE64(byte[] key){
        return org.apache.commons.codec.binary.Base64.encodeBase64String(key);
    }

    public static String sign(byte[] data, String privateKey)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(privateKey);

        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey2);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }

    public static String sign2(byte[] data, PrivateKey privateKey)
            throws Exception
    {
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }

    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(publicKey);

        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(publicKey2);
        signature.update(data);

        return signature.verify(decryptBASE64(sign));
    }

    public static byte[] encryptMD5(byte[] data)
            throws Exception
    {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(data);
        return md5.digest();
    }

    public static byte[] encryptSHA(byte[] data)
            throws Exception
    {
        MessageDigest sha = MessageDigest.getInstance("SHA");
        sha.update(data);
        return sha.digest();
    }

    public static String getPublicKey(Map<String, Object> keyMap)
            throws Exception
    {
        Key key = (Key)keyMap.get("RSAPublicKey");
        return encryptBASE64(key.getEncoded());
    }

    public static String getPrivateKey(Map<String, Object> keyMap)
            throws Exception
    {
        Key key = (Key)keyMap.get("RSAPrivateKey");
        return encryptBASE64(key.getEncoded());
    }

    public static Map<String, Object> initKey()
            throws Exception
    {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(KEY_SIZE_2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();

        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();

        Map keyMap = new HashMap(2);
        keyMap.put("RSAPublicKey", publicKey);
        keyMap.put("RSAPrivateKey", privateKey);

        return keyMap;
    }

    public static Map<String, Object> initKey(int keySize)
            throws Exception
    {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(keySize);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();

        RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();

        Map keyMap = new HashMap(2);
        keyMap.put("RSAPublicKey", publicKey);
        keyMap.put("RSAPrivateKey", privateKey);

        return keyMap;
    }

    public static byte[] encryptByPrivateKey(byte[] data, String key)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(key);

        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(1, privateKey);

        return cipher.doFinal(data);
    }

    public static byte[] encryptByPublicKeyF(byte[] data, String publicKey)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicK = keyFactory.generatePublic(x509KeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(1, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;

        int i = 0;

        while (inputLen - offSet > 0)
        {
            byte[] cache;
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            ++i;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    public static byte[] decryptByPrivateKeyF(byte[] encryptedData, String privateKey)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(2, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;

        int i = 0;

        while (inputLen - offSet > 0)
        {
            byte[] cache;
            if (inputLen - offSet > MAX_DECRYPT_BLOCK)
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            ++i;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    public static byte[] decryptByPublicKey(byte[] data, String key)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(key);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(2, publicKey);

        return cipher.doFinal(data);
    }

    public static Key getPublicKeyByString(String key) throws Exception {
        byte[] keyBytes = decryptBASE64(key);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        return publicKey;
    }

    public static byte[] encryptByPublicKey(byte[] data, String key)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(key);

        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(1, publicKey);

        return cipher.doFinal(data);
    }

    public static byte[] decryptByPrivateKey(byte[] data, String key)
            throws Exception
    {
        byte[] keyBytes = decryptBASE64(key);

        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(2, privateKey);

        return cipher.doFinal(data);
    }

    public static Key getPrivateKeyByString(String key) throws Exception {
        byte[] keyBytes = decryptBASE64(key);

        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        return privateKey;
    }

    /**
     *
     * @Title: getKeyMap
     * @todo: 获取公钥和密钥
     * @param keyNum
     * @return
     * @return Map<String,String>
     * @author majinchao
     * @date 2015年5月14日 下午5:28:48
     */
    public static Map<String, String> getKeyMap(int keyNum) throws Exception {
        Map map = new HashMap();
        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        keyGen.initialize(keyNum, random);
        KeyPair pair = keyGen.generateKeyPair();
        PrivateKey priv = pair.getPrivate();
        PublicKey pub = pair.getPublic();

        String privateStr = encryptBASE64(priv.getEncoded());
        String publicStr = encryptBASE64(pub.getEncoded());
        map.put("publicKey", publicStr);
        map.put("privateKey", privateStr);
        return map;
    }

    /**
     *
     * @Title: encreptData
     * @todo: 加密数据
     * @param content
     * @param pulicKey
     * @throws Exception
     * @return String
     */
    public static String encryptData(String content, String pulicKey, String encoding) throws Exception {
        Cipher rsaCipher = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache = null;
        int i = 0;
        int inputLen = content.getBytes(encoding).length;
        rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(1, getPublicKeyByString(pulicKey));
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK)
                cache = rsaCipher.doFinal(content.getBytes(encoding), offSet,
                        MAX_ENCRYPT_BLOCK);
            else {
                cache = rsaCipher.doFinal(content.getBytes(encoding), offSet,
                        inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            ++i;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptBASE64(encryptedData);
    }

    public static String decryptData(String content, String privateKey, String encoding) throws Exception {
        Cipher rsaCipher = null;
        int offSet2 = 0;
        byte[] cache2 = null;
        int i2 = 0;
        byte[] contentByte = decryptBASE64(content);

        int inputLen2 = contentByte.length;
        ByteArrayOutputStream out2 = new ByteArrayOutputStream();
        rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        rsaCipher.init(2, getPrivateKeyByString(privateKey));

        while (inputLen2 - offSet2 > 0) {
            if (inputLen2 - offSet2 > MAX_DECRYPT_BLOCK)
                cache2 = rsaCipher.doFinal(contentByte, offSet2, MAX_DECRYPT_BLOCK);
            else {
                cache2 = rsaCipher.doFinal(contentByte, offSet2, inputLen2
                        - offSet2);
            }
            out2.write(cache2, 0, cache2.length);
            ++i2;
            offSet2 = i2 * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData2 = out2.toByteArray();
        out2.close();
        return new String(decryptedData2, encoding);
    }

    public static boolean verify(byte[] data, byte[] publicKey, byte[] sign)
            throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("SHA1withRSA");
        signature.initVerify(pubKey);
        signature.update(data);
        return signature.verify(sign);
    }

    /**
     * 加密方法 source： 源数据
     */
    public static String encryptByPublicKey(String source, String publicKey)
            throws Exception {
        Key key = getPublicKeyByString(publicKey);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(CipherConfigure.RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return new String(Base64.encodeBase64(b1), CipherConfigure.CHAR_ENCODING);
    }

    /**
     * 加密方法 source： 源数据
     */
    public static String encryptByPrivateKey(String source, String privateKey)
            throws Exception {
        Key key = getPrivateKeyByString(privateKey);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(CipherConfigure.RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] b = source.getBytes();
        /** 执行加密操作 */
        byte[] b1 = cipher.doFinal(b);
        return new String(Base64.encodeBase64(b1), CipherConfigure.CHAR_ENCODING);
    }

    /**
     * 解密算法 cryptograph:密文
     */
    public static String decryptByPrivateKey(String cryptograph, String privateKey)
            throws Exception {
        Key key = getPrivateKeyByString(privateKey);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(CipherConfigure.RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] b1 = Base64.decodeBase64(cryptograph.getBytes());
        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);

    }

    /**
     * 解密算法 cryptograph:密文
     */
    public static String decryptByPublicKey(String cryptograph, String publishKey)
            throws Exception {
        Key key = getPublicKeyByString(publishKey);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(CipherConfigure.RSA_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] b1 = Base64.decodeBase64(cryptograph.getBytes());
        /** 执行解密操作 */
        byte[] b = cipher.doFinal(b1);
        return new String(b);
    }

}